<?php
namespace application\datatypes;
use application\datatypes\DataType;
use application\models\Tag;
use application\system\Permalink as SystemPermalink;

class UserInteraction extends DataType {
	public static $name = 'User Interaction';
	public static $fields = array();
	
	
	public static function validate($field, $data, $results) {
		$interaction = getFieldMetaData($field->cf_id, 'interaction');
		if($field->cf_required && !$data['interactions_'.$field->cf_id]) {
			$results['errors'][] = $field->cf_display_name.' is required.';
		}
		else {
			$results['db_fields']['interactions'][$interaction] = $data['interactions_'.$field->cf_id];
		}
		
		return $results;
	}
	
	public static function formHeader($field) {
		Modulator()->includeScript('jquery');
		Modulator()->includeScript(getCommonFile('concerto/admin/livesearch.js'));
		?>
		<script type="text/javascript">
			$(document).ready(function() {
				$('.user-interaction').livesearch('multiple');
			});
		</script>
		<?php
	}
	
	public static function display($formElements) {
		if($formElements['elements']['element']) :
			?>
			
			<fieldset class="tags-field">
			<header><?=$formElements['display']?></header>
			<section class="inner">
			<?php
			echo $formElelements['elements']['search'];
			echo $formElements['elements']['element'];?>
			</section>
			</fieldset>
		<?php endif;
	}
	
	public static function build($field, $data) {
		// Get field meta data
		$interaction = getFieldMetaData($field->cf_id, 'interaction');

		
		$contentId = $data['content_id'];
		

		
		/** Display tags */
		$formElements = array('column'=>'interactions', 'display'=>$field->cf_display_name, 'data_type'=>'UserInteractions', 'elements'=>array());
	
		// Get preexisting users
		$existingUsers = $data['interactions_'.$field->cf_id.''];
		
		if(!$existingUsers) $existingUsers = array();
		// Get list of users
		
		$users = DB()->getResults("SELECT * FROM `cn_users` ORDER BY `user_id`");
		$userSelect = '<select multiple="multiple" class="user-interaction" name="interactions_'.$field->cf_id.'[]" id="interactions_'.$field->cf_id.'">';
		
		foreach($users as $user) {
			if(in_array($user->user_id, $existingUsers)) 
				$userSelect .= '<option selected="selected" value="'.$user->user_id.'">'.displayName($user->user_id).'</option>';
			else
				$userSelect .= '<option value="'.$user->user_id.'">'.displayName($user->user_id).'</option>';
		}
		
		$userSelect .= '</select>';
		$formElements['elements']['element'] = $userSelect;
		
		
		return $formElements;
	
	}
	
	public static function save() {
		$field = $_REQUEST['field'];
		
		foreach($_REQUEST as $key=>$value) {
			if(substr($key, 0, 5) == 'meta_') {
				$varname = substr($key, 5);
				$count = DB()->getCount("SELECT * FROM `cn_field_meta` WHERE `cfm_key`='$varname' AND `cfm_field`='$field'");
				if(!$count) {
					$insert = array('cfm_key'=>$varname, 'cfm_value'=>$value, 'cfm_field'=>$field);
					DB()->insert('cn_field_meta', $insert);
				}
				else {
					DB()->query("UPDATE `cn_field_meta` SET `cfm_value`='$value' WHERE `cfm_key`='$varname' AND `cfm_field`='$field'");
				}
			}
		}
	}
	
	public static function endForm($field, $data, $id, $type) {
		$interaction = getFieldMetaData($field->cf_id, 'interaction');
		$interactions = $data['interactions'][$interaction];
		if(!$interactions) $interactions = array();
		
		
		
		$existings = DB()->getResults("SELECT * FROM `cn_user_content_relations` INNER JOIN `cn_content` ON `content_id`=`ucr_content` WHERE `ucr_interaction`='$interaction' AND `content_id`='$id'");
		
		$currentInteractions = array();
		foreach($existings as $existing) {
			$currentInteractions[$existing->ucr_id] = $existing->ucr_user;
		}
		
		// Get tags that we don't have to add
		$noNeed = array_intersect($interactions, $currentInteractions);
		
		// Get tags we need to remove
		$toDelete = array_keys(array_diff($currentInteractions, $noNeed));
		$toDelete = "'".implode("', '", $toDelete)."'";
		
		// Get tags we need to add
		$toAdd = array_diff($interactions, $currentInteractions);
		

		
		DB()->query("DELETE FROM `cn_user_content_relations` WHERE `ucr_id` IN ($toDelete) AND `ucr_content`='$id'");
		foreach($toAdd as $add) {
			DB()->insert('cn_user_content_relations', array('ucr_content'=>$id, 'ucr_user'=>$add, 'ucr_interaction'=>$interaction));
		}
	}
	
	public static function fromDB($fields, $field, $data) {
		$column = $field->cf_column;
		$contentId = $data['content_id'];
		$interaction = getFieldMetaData($field->cf_id, 'interaction');
		$existingInteractions = DB()->getVarArray("SELECT `ucr_user` FROM `cn_user_content_relations` WHERE `ucr_content`='$contentId'");
	

		return array('interactions_'.$field->cf_id => $existingInteractions);
	}
	
	public static function editForm($field) {
		// Get all interactions for parents
		$contentType = $field->getContentType();
		$parents = unserialize(getOption('c'.$contentType.'_allowed_parents'));
		
		if(is_array($parents)) {
			$parentInteractions = DB()->getResults("SELECT * FROM `cn_content_interactions` WHERE `ci_content_type` IN (".\application\utilities\Utility::sqlImplodedArray($parents).") ORDER BY `ci_name`");
		}
		
		$availableInteractions = DB()->getResults("SELECT * FROM `cn_content_interactions` WHERE `ci_content_type`='$contentType'");
		?>
			<input type="hidden" name="field_id" value="<?=$field->getId()?>"/>
			<ul class="form-fields">
			<li>
			<label>Field Display Name</label>
			<input type="text" name="field_display_name" class="big wide" value="<?=$field->getDisplayName()?>"/>
			</li>
			<li>
			<label>Field Description</label>
			<textarea name="field_description" class="wide"><?=$field->getDescription()?></textarea>
			</li>
			<li>
				<label>Interaction</label>
				<select name="meta_interaction">
					<?php 
					foreach($availableInteractions as $interaction) : ?>
					<option <?= ($field->getMeta('interaction') == $interaction->ci_id) ? 'selected="selected"' : ''?> value="<?=$interaction->ci_id?>"><?=$interaction->ci_name?></option>
					<?php endforeach;?>
				</select>
			</li>
			<li>
				<label><input type="radio" name="meta_userfilter" value="all"/> Choose from all users</label>
				<?php if(is_array($parents)) : ?>
				<label><input type="radio" name="meta_userfilter" value="interaction"/> Choose from users with interaction 
					<select name="meta_userfilter_interaction">
						<?php foreach($parentInteractions as $interaction) : ?>
						<option value="<?=$interaction->ci_id?>" <?=($interaction->ci_id == $field->getMeta('userfilter_interaction')) ? 'selected="selected"' : ''?>><?=$interaction->ci_name?></option>
						<?php endforeach;?>
					</select> with this content's parent</label>
				<?php endif;?>
			</li>
			</ul>
			<?php
	}	
	
	public static function prepareData($field, $data, $params) {
		$interaction = $data['interactions_'.$field->cf_id];
		
		
		
		return $interaction;
	}
	
}
?>